package com.suray.wcs.service.thread;

import com.suray.basic.wcs.path.enums.NodeType;
import com.suray.basic.wcs.utils.Coord;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.wcs.res.enums.RgvStatus;
import com.suray.wcs.service.pojo.Rgv;
import com.suray.wcs.service.rescontact.ToRes;
import com.suray.wcs.service.system.entity.NodeDB;
import com.suray.wcs.service.system.service.impl.NodeDBServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 自动定位线程
 */
public class AutomaticPositioning {
    private static final NodeDBServiceImpl nodeDBService = SpringContextHolder.getBean(NodeDBServiceImpl.class);
    private static Logger log = LoggerFactory.getLogger(AutomaticPositioning.class);

    private Rgv rgv;

    public AutomaticPositioning(Rgv rgv) {
        this.rgv = rgv;
    }

    public void start() {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleWithFixedDelay(() -> {
            Thread.currentThread().setName(rgv.getRgvName() + "自动定位线程");
            if (rgv.getCurLocation() == null && rgv.getRgvStatus().equals(RgvStatus.READY) && rgv.getGroundCode() != null) {
                NodeDB nodedb = nodeDBService.findByBarcode(rgv.getGroundCode());
                // 存在这个条码对应的位置
                if (nodedb != null) {
                    if (nodedb.getGridType() != NodeType.L) {
                        try {
                            ToRes.getInstance(rgv).changeLocation(null, new Coord(nodedb.getGridx(), nodedb.getGridy(), nodedb.getGridz()));
                            log.info(rgv.getRgvName()+"自动定位成功，当前位置"+rgv.getCurLocation());
                        }catch (Exception e){
                            log.warn(rgv.getRgvName()+"自动定位失败"+e.getMessage());
                        }

                    }
                }
            }

        },0,5000, TimeUnit.MILLISECONDS);
    }
}
